import { useState } from "react";
import Taro, { useRouter } from "@tarojs/taro";
import { Text, View } from "@tarojs/components";
import { useBoolean } from "ahooks";

import ByCol from "@/components/ui/ByCol";
import ByRow from "@/components/ui/ByRow";
import Card from "@/components/common/Card";
import ByIcon from "@/components/ui/ByIcon";
import GoldBill from "./component/GoldBill";
import TabsTag from "@/components/app/TabsTag";
import Sticky from "@/components/app/Sticky";
import PopupInfo from "./component/PopupInfo";
import Moment from "@/components/app/Moment";
import Divider from "@/components/app/Divider";
import ByCellGroup from "@/components/ui/ByCellGroup";
import ProjectBaseInfo from "./component/ProjectBaseInfo";
import PaneApplication from "./component/PaneApplication";
import ProjectExtenceInfo from "./component/ProjectExtenceInfo";
import PaneContructionTodos from "./component/PaneContructionTodos";

import useFetch from "@/hooks/useFetch";
import ApiCrm from "@/api/crm";

import { CustomerItem } from "@/types/customer";
import ByPopup from "@/components/ui/ByPopup";
import useAuth from "@/hooks/useAuth";

const tabs = [
  { label: "待办", value: 0 },
  { label: "应用", value: -1 },
  { label: "已办", value: 1 },
];

// complateState 88是完工。startstate =1 是开工,state 33 表示计划待拟定,88表示已拟定

// 判断是否已绑定模块ID
const getMkId = (val: string) => {
  return val && val != "0" ? val : undefined;
};

export default () => {
  const { params } = useRouter<{
    draftCustomerId: `${number}`;
    intentCustomerId: `${number}`;
  }>();

  const draftCustomerId = Number(params.draftCustomerId);
  const intentCustomerId = Number(params.intentCustomerId);

  const [tabActive, setTabActive] = useState(tabs[0]["value"]);

  const detailApiUrl = intentCustomerId
    ? ApiCrm.customerDetail
    : ApiCrm.draftCustomerDetail;

  // 根据意向ID, 获取客户信息
  const { data } = useFetch<CustomerItem>(detailApiUrl, {
    // 偷懒做法
    defaultParams: [{ draftCustomerId, intentCustomerId }],
    onAfter: (res) => res.intentCustomer || res.draftCustomer,
  });

  const [visible, { setTrue, setFalse }] = useBoolean();

  // 已成为意向客户
  const isIntentCustomer = !!data?.intentCustomerId;


  // 判断是否拥有目标权限
  const getAuth = useAuth()

  // 是否显示质保金：已成为意向客户 && 拥有查看的权限
  const showQuantiyBill = isIntentCustomer && getAuth("WeiXinApp_quantiyGoldBill")

  console.log('deftail')
  return (
    <>
      {data && (
        <View className="p-3">
          <Card className="mb-3">
            <ByRow align="center">
              <ByCol span="auto">
                <View className="text-lg font-bold">{data.customerName}</View>
                <View className="mt-3 text-sm text-third">
                  <ByIcon name="Location" size={24} />
                  <Text className="pl-2">
                    {data.decorationFullAddress || "--"}
                  </Text>
                </View>
              </ByCol>

              <ByCol span="none" className="text-right">
                <ByIcon
                  name="Phone"
                  size={40}
                  className="text-primary"
                  onClick={() =>
                    Taro.makePhoneCall({ phoneNumber: data.mobileTelephone })
                  }
                />
                {isIntentCustomer && (
                  <View className="mt-3 text-sm text-primary" onClick={setTrue}>
                    <Text>项目信息</Text>
                    <ByIcon name="ArrowRight" />
                  </View>
                )}
              </ByCol>
            </ByRow>

            <Divider />

            <ByRow align="center">
              <ByCol span="auto">
                <View className="text-sm">{data?.createUser} 创建</View>
                <View className="mt-2 text-sm text-third">
                  <Moment value={data?.createDate} type="full" />
                </View>
              </ByCol>
              <ByIcon name="More" />
            </ByRow>
          </Card>

          {/* <View>todo: 拥有该权限（的项目经理）才可以看到风险金和质保金</View> */}
          {showQuantiyBill && <GoldBill intentCustomerId={intentCustomerId} />}

          {!isIntentCustomer ? (
            <>
              <ByCellGroup title="基本信息" className="mt-6">
                <ProjectBaseInfo source={data} />
              </ByCellGroup>

              <ByCellGroup title="扩展信息" className="mt-6">
                <ProjectExtenceInfo source={data} />
              </ByCellGroup>
            </>
          ) : (
            <>
              <Sticky position="top" className="py-3 bg-page z-10">
                <TabsTag
                  mode="auto"
                  items={tabs}
                  active={tabActive}
                  onChange={setTabActive}
                />
              </Sticky>

              {tabActive === -1 ? (
                <PaneApplication
                  intentCustomerId={intentCustomerId}
                  projectid={getMkId(data.mkId)}
                />
              ) : (
                <PaneContructionTodos
                  status={tabActive}
                  intentCustomerId={intentCustomerId}
                />
              )}
            </>
          )}
        </View>
      )}

      {/* <PageContainer round show={visible} onAfterLeave={setFalse}>
        {visible && (
          <PopupInfo
            source={data}
            intentCustomerId={intentCustomerId}
            onCancel={setFalse}
          />
        )}
      </PageContainer> */}

      {visible && (
        <ByPopup position="bottom">
          <PopupInfo
            source={data}
            intentCustomerId={intentCustomerId}
            onCancel={setFalse}
          />
        </ByPopup>
      )}
    </>
  );
};
